import 'package:cached_network_image/cached_network_image.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/conform_dialog.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/modules/device/ui/widgets/pairnet_process_button.dart';
import 'package:casdon/modules/device/application/notification/pair_net_notifier.dart';
import 'package:casdon/modules/device/domain/states/pair_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

class DevicePairnetListItem extends ConsumerWidget {
  final ThingSmartDeviceModel device;
  final Future<void> Function(ThingSmartDeviceModel device) onIdleTap;
  final Future<void> Function(
    ThingSmartDeviceModel device,
    bool isWifiConfigError,
  ) onFailedTap;
  const DevicePairnetListItem({
    super.key,
    required this.device,
    required this.onIdleTap,
    required this.onFailedTap,
  });

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final normalizedUuid = _normalizeUuid(device.uuid);
    final devicePairState = ref.watch(
      pairNetProvider.select(
        (list) => list.firstWhere(
          (e) => _normalizeUuid(e.deviceModel?.uuid ?? '') == normalizedUuid,
          orElse: () => DevicePairState(
            deviceModel: device,
            state: PairState.idle,
            errorCode: 0,
            errorMsg: '',
          ),
        ),
      ),
    );
    final state = devicePairState.state;
    final successDevice = devicePairState.deviceModel;
    final isWifiConfigError = devicePairState.isWifiConfigError;
    final errMsg = devicePairState.outErrorMsg;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: Padding(
        padding: EdgeInsets.all(16.r),
        child: Row(
          children: [
            // 设备图标
            SizedBox(
              width: 45.w,
              height: 45.w,
              child: Stack(
                clipBehavior: Clip.none,
                children: [
                  CachedNetworkImage(
                    imageUrl: device.iconUrl,
                    width: 45.w,
                    height: 45.w,
                    errorWidget: (_, __, ___) => Icon(Icons.devices),
                  ),
                  if (state == PairState.success)
                    Positioned(
                      top: -4.r,
                      right: -4.r,
                      child: CircleAvatar(
                        radius: 10.5.r,
                        backgroundColor: const Color(0xFF2BA471),
                        child: Icon(
                          Icons.check,
                          color: Colors.white,
                          size: 10.5.r,
                        ),
                      ),
                    ),
                ],
              ),
            ),
            SizedBox(width: 16.w),

            // 设备信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    _resolveDeviceName(successDevice, device),
                    style: TextStyle(
                      fontSize: 14.r,
                      fontWeight: FontWeight.w500,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    // _getStatusText(state),
                    errMsg,
                    style: TextStyle(fontSize: 12.r, color: Color(0xFFD54941)),
                  ),
                ],
              ),
            ),

            // 状态按钮
            PairnetProcessButton(
              state: state,
              isQueued: devicePairState.inQueue,
              onIdleTap: () => onIdleTap(device),
              onFailedTap: () => onFailedTap(device, isWifiConfigError),
              onSuccessTap: () {
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  _showRenameDialog(context, ref, device);
                });
              },
            ),
          ],
        ),
      ),
    );
  }

  void _showRenameDialog(
    BuildContext context,
    WidgetRef ref,
    ThingSmartDeviceModel device,
  ) async {
    final normalizedUuid = _normalizeUuid(device.uuid);
    if (!context.mounted) return;
    final result = await showInputDialog(
      context: context,
      title: '修改名称',
      hintText: '输入新名称',
    );
    if (result != null && result.isNotEmpty) {
      final targetDevice =
          ref
              .read(pairNetProvider)
              .firstWhere(
                (element) =>
                    _normalizeUuid(element.deviceModel?.uuid ?? '') ==
                    normalizedUuid,
                orElse: () => DevicePairState(
                  deviceModel: device,
                  state: PairState.idle,
                  errorCode: 0,
                  errorMsg: '',
                ),
              )
              .deviceModel ??
          device;
      if (targetDevice.devId == null) {
        ToastUtil.show('设备信息不完整，无法修改名称');
        return;
      }
      final success = await TuyaService().renameDevice(
        deviceId: targetDevice.devId!,
        name: result.trim(),
      );
      if (success) {
        ref
            .read(pairNetProvider.notifier)
            .updateDeviceName(uuid: targetDevice.uuid, name: result.trim());
        ToastUtil.show('设备名称已修改为 $result');
      } else {
        ToastUtil.show('设备名称修改失败');
      }
    }
  }

  String _resolveDeviceName(
    ThingSmartDeviceModel? successDevice,
    ThingSmartDeviceModel fallback,
  ) {
    final name = successDevice?.name;
    if (name != null && name.trim().isNotEmpty) {
      return name;
    }
    return fallback.name;
  }
}

String _normalizeUuid(String uuid) => uuid.toLowerCase();
